// import { defineStore } from 'pinia'

// export const useMainStore = defineStore({
//     id: 'main',
//     state: () => ({
//         name: '超级管理员',
//     }),
//     getters: {
//         nameLength: (state) => state.name.length,
//     },
//     actions: {
//         async insertPost(data: string) {
//             // 可以做异步
//             // await doAjaxRequest(data);
//             this.name = data
//         },
//     },
// })

import { defineStore } from 'pinia'
import router from '@/router'

// 定义用户信息的类型
interface UserInfo {
  username: string
  name: string
  avatar: string
  token: string
}

export const useUserStore = defineStore('main', {
  state: (): { userInfo: UserInfo; token: string } => {
    const storedUserInfo = localStorage.getItem('userInfo')
    const userInfo: UserInfo = storedUserInfo
      ? JSON.parse(storedUserInfo)
      : {
          username: '',
          name: '',
          avatar: '',
          token: '',
        }
    const token = localStorage.getItem('token') || ''
    return {
      userInfo,
      token,
    }
  },
  getters: {
    // 示例 getter，可根据需求添加更多
    nameLength: (state) => state.userInfo.name.length,
  },
  actions: {
    async loginIn(data: UserInfo) {
      this.userInfo = data
      localStorage.setItem('userInfo', JSON.stringify(data))
      localStorage.setItem('token', data.token)
      await router.push({
        path: '/',
      })
    },
  },
})
